const fs = require('fs');
const path = require('path');
const print = require('idiv-utils').print;
const fsStat = fs.stat;


// 复制文件
const copy = function (src, dst) {
	fs.readdir(src, function (err, paths) {
		if(err) throw err;
		handleFile(paths, src, dst);
	});
};

// 处理文件
const handleFile = function (paths, src, dst) {
	paths.forEach(function (path) {
		var srcPath = `${src}/${path}`;
		var tarPath = `${dst}/${path}`;
		fsStat(srcPath, function (err, stat) {
			if(err) throw err;

			if(stat.isFile()) {
				return fs.createReadStream(srcPath).pipe(fs.createWriteStream(tarPath));
			} else if(stat.isDirectory()) {
				// 递归调用ensureExists
				return ensureExists(srcPath, tarPath, copy);
			} else {
				throw new Error('发生未知错误');
			}
		});
	});
};

// 确保目标目录存在， 不存在就创建一个
const ensureExists = function (src, dst, cb) {
	fs.exists(dst, function (exists) {
		if(exists) {
			cb(src, dst);
		} else {
			// 不存在就创建一个
			fs.mkdir(dst, function () {
				cb(src, dst);
			});
		}
	});
};

// 启动任务
const start = function (appName) {
	if(!appName) {
		print('项目名称不能为空！', 91);
		return;
	}
	// 模版路径, 项目路径
	const templatePath = path.resolve(__dirname, 'template');
	const appPath = path.resolve(process.cwd(), appName);

	ensureExists(templatePath, appPath, copy);
};


module.exports = start;